<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { queryTotal } from '@api/question'
import { Message as ElMessage } from 'element-ui'
import { utils } from 'xlsx'
import { sheet2blob } from '@/utils/download/getDownloadInfo'
import { downloadBlobFile } from '@/utils/download'

const props = defineProps({
  areaIds: {
    type: Object,
    default: () => {},
  },
  type: {
    type: String,
    default: 'region',
  },
})

const streetTableProps = computed(() => {
  if (props.type === 'satisfaction') {
    return [
      {
        name: '区域',
        prop: 'name',
      },
      {
        name: '问卷数',
        prop: 'total',
      },
      {
        name: '目标数',
        prop: 'satisfactionTotal',
      },
      // {
      //   name: '建议目标数',
      //   prop: 'proposalTotal',
      // },
      {
        name: '完成率',
        prop: 'completionRate',
      },
    ]
  } else {
    return [
      {
        name: '区域',
        prop: 'name',
      },
      {
        name: '待提交',
        prop: 'unCommitTotal',
      },
      {
        name: '待审核',
        prop: 'unCheckTotal',
      },
      {
        name: '通过',
        prop: 'passTotal',
      },
      {
        name: '退回',
        prop: 'backTotal',
      },
    ]
  }
})

const totalForm = reactive({})

const totalList = ref([])
const loading = ref(false)

// 统计列表数据只与类型、筛选有关
// 最多只能筛选到街道一级
const getTotalList = () => {
  loading.value = true
  totalList.value = []
  let special = false
  if (props.type === 'satisfaction') {
    special = true
  }
  queryTotal(
    {
      districtId: props.areaIds.districtId,
      streetId: props.areaIds.streetId,
      regionId: props.areaIds.regionId,
      communityId: props.areaIds.communityId,
      type: props.type,
    },
    special
  )
    .then((res) => {
      if (res.success) {
        totalList.value = res.data
      } else {
        // console.log('err')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const download = (name) => {
  if (loading.value) {
    ElMessage.warning('数据加载中，请稍后再试')
    emits('downloaded')
    return
  }
  // console.log(totalList.value)
  const header = streetTableProps.value.map((item) => item.name)
  const data = totalList.value.map((item) => {
    return streetTableProps.value.map((prop) => {
      if (prop.prop === 'completionRate') {
        return item.satisfactionTotal
          ? (((item.total ?? 0) / item.satisfactionTotal) * 100).toFixed(2) +
              '%'
          : item.total
          ? '-'
          : 0 + '%'
      }
      return item[prop.prop]
    })
  })
  const exportData = [header, ...data]
  const worksheet = utils.aoa_to_sheet(exportData)
  const blob = sheet2blob([
    {
      sheet: worksheet,
    },
  ])
  downloadBlobFile(
    {
      data: blob,
    },
    name + '填报统计表.xlsx'
  )
  emits('downloaded')
}

const emits = defineEmits(['tabClick', 'downloaded'])

const handleCurrentChange = () => {}

onMounted(() => {
  // console.log(props.type)
  getTotalList()
})

const refresh = () => {
  getTotalList()
}

defineExpose({
  refresh,
  download,
})

const handlClickTable = (row) => {
  if (props.type === 'satisfaction') {
    return
  }
  emits('tabClick', row)
}
</script>

<template>
  <div class="statistics-total">
    <el-table
      :data="totalList"
      highlight-current-row
      @current-change="handleCurrentChange"
      @row-click="handlClickTable"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column
        v-for="(item, index) in streetTableProps"
        :key="index"
        :label="item.name"
        :prop="item.prop"
      >
        <!--完成率-->
        <template v-if="item.prop === 'completionRate'" #default="{ row }">
          <span>{{
            row.satisfactionTotal
              ? (((row.total ?? 0) / row.satisfactionTotal) * 100).toFixed(2) +
                '%'
              : row.total
              ? '-'
              : 0 + '%'
          }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped lang="scss"></style>
